package org.summerframework.component.upload.util;

import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.tag.id3.AbstractID3v2Tag;

public class MusicUtil {

	private static final int START = 6;

	/**
	 * 解析音乐文件得到歌名,演唱者,专辑等信息
	 * @param url
	 * @param originalFilename
	 * @return
	 */
	public static String parserMusic(String url, String originalFilename) {
		StringBuilder sb = new StringBuilder();
		try {

			MP3File mp3File = new MP3File(url.replace("\\", "/"));

			AbstractID3v2Tag id3v2tag = mp3File.getID3v2Tag();
			if (id3v2tag == null) {
				sb.append(originalFilename.substring(0, originalFilename.lastIndexOf(".")) + ",未知,未知,未知");
			} else {
				if (id3v2tag.frameMap.get("TIT2") != null) {
					String songName = new String(id3v2tag.frameMap.get("TIT2").toString().getBytes("ISO-8859-1"), "GB2312");
					if (songName.contains("?")) {
						songName = new String(id3v2tag.frameMap.get("TIT2").toString());
						sb.append(songName.substring(START, songName.length() - 3));
					} else {
						sb.append(songName.substring(START, songName.length() - 3));
					}
				} else {
					sb.append(originalFilename.substring(0, originalFilename.lastIndexOf(".")));
				}

				if (id3v2tag.frameMap.get("TPE1") != null) {
					String singer = new String(id3v2tag.frameMap.get("TPE1").toString().getBytes("ISO-8859-1"), "GB2312");
					if (singer.contains("?")) {
						singer = new String(id3v2tag.frameMap.get("TPE1").toString());
						sb.append("," + singer.substring(START, singer.length() - 3));
					} else {
						sb.append("," + singer.substring(START, singer.length() - 3));
					}
				} else {
					sb.append(",未知");
				}

				if (id3v2tag.frameMap.get("TALB") != null) {
					String album = new String(id3v2tag.frameMap.get("TALB").toString().getBytes("ISO-8859-1"), "GB2312");
					if (album.contains("?")) {
						album = new String(id3v2tag.frameMap.get("TALB").toString());
						sb.append("," + album.substring(START, album.length() - 3));
					} else {
						sb.append("," + album.substring(START, album.length() - 3));
					}

				} else {
					sb.append(",未知");
				}

				sb.append("," + mp3File.getMP3AudioHeader().getTrackLengthAsString());
			}
		} catch (Exception e) {
			e.printStackTrace();
			sb.append("未知,未知,未知,未知");
		}
		return sb.toString();
	}

}
